package bar.dark.lee.manager.card;

import java.util.ArrayList;
import java.util.HashMap;

import bar.dark.lee.BDConstents;
import bar.dark.lee.R;
import bar.dark.lee.SuperActivity;
import bar.dark.lee.common.BDUtil;
import bar.dark.lee.common.DBSQLite;
import bar.dark.lee.common.RadioDialogActivity;
import bar.dark.lee.common.DBSQLite.ParseSelectData;
import bar.dark.lee.insert.InsertInActivity;
import bar.dark.lee.insert.InsertOutActivity;
import bar.dark.lee.manager.money.BankbookData;
import bar.dark.lee.widget.WidgetGetSqlQuery;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.AdapterView.OnItemSelectedListener;

public class CheckCardUpdataActivity extends SuperActivity
{
	public static final int REQUEST_CHECKCARD = 0;

	private DBSQLite sql;
	
	private EditText name;
	private TextView linkTextView;
	
	private Button deleteButton;
	private Button updateButton;
	
	private CheckCardData data;
	
	private ArrayList<BankbookData> bankbookDataList;
	
	private ListView listView;
	
	private View resultView;
	
	private int addflag;
	
	private EditText orderEditText;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		sql = DBSQLite.getInstance(this);
		
		setTitle("체크카드 수정");
		setGoneTipButton();
		
		setContentView(R.layout.manager_checkcard_update_activity);
		
		setFindView();
		setClickListener();
		new ShowDialog().execute(0);
	}
	
	private void setFindView()
	{
		name = (EditText) findViewById(R.id.checkCardUpdateName);
		linkTextView = (TextView) findViewById(R.id.checkCardUpdateLinkTypeTextView);
		deleteButton = (Button) findViewById(R.id.checkCardDeleteButton);
		updateButton = (Button) findViewById(R.id.checkCardUpdateButton);
		
		listView = (ListView) findViewById(R.id.checkCardUpdateListView);
		
		resultView = getLayoutInflater().inflate(R.layout.view_no_result, null);
		
		orderEditText = (EditText) findViewById(R.id.checkcardUpdateOrder);
	}

	private void setData()
	{
		Intent intent = getIntent();
		data = intent.getParcelableExtra(CheckCardActivity.CHECKCARD_DATA);
		
		bankbookDataList = new ArrayList<BankbookData>();
		
		sql.selectMapTile(this, "SELECT id, name, money FROM bankbook;", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int idIdx = c.getColumnIndex("id");
				int nameIndex = c.getColumnIndex("name");
				int moneyIdx = c.getColumnIndex("money");
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					BankbookData data = new BankbookData();
					
					data.setId(c.getInt(idIdx) + "");
					data.setName(c.getString(nameIndex));
					data.setMoney(c.getString(moneyIdx));
					
					sql.selectMapTile(superContext, "SELECT addflag FROM bankbook_detail " +
							"WHERE linkid = " + data.getId() + ";", 
							new ParseSelectData()
					{
						@Override
						public void resultData(Cursor c)
						{
							int addflagIdx = c.getColumnIndex("addflag");
							addflag = -1;
							c.moveToFirst();
							
							for (int i = 0; i < c.getCount(); i++)
							{
								addflag = c.getInt(addflagIdx);
								c.moveToNext();
							}
						}
					});
					
					if (addflag == 1)
					{
						data.setFlag("1");
					}
					else
					{
						data.setFlag("0");
					}
					
					bankbookDataList.add(data);
					
					c.moveToNext();
				}
			}
		});
	}
	
	private OnItemClickListener onItemClicklistener = new OnItemClickListener()
	{
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
				long arg3)
		{
			if (bankbookDataList.size() < 1)
			{
				return;
			}
			
			String bankBookName = bankbookDataList.get(pos).getName();
			linkTextView.setText(bankBookName);
		}
	};
	
	private void setClickListener()
	{
		deleteButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				AlertDialog.Builder dia = new AlertDialog.Builder(CheckCardUpdataActivity.this);
				dia.setTitle("알림");
				dia.setMessage("체크카드를 삭제하시겠습니까? 체크카드가 삭제 될 경우 연결된 내역은 수정 삭제가 불가능합니다.");
				
				dia.setPositiveButton("삭제", new DialogInterface.OnClickListener()
				{
					@Override
					public void onClick(DialogInterface dialog, int which)
					{
						new ShowDialog().execute(1);
						dialog.dismiss();
					}
				});
				
				dia.setNegativeButton("취소", new DialogInterface.OnClickListener()
				{
					@Override
					public void onClick(DialogInterface dialog, int which)
					{
						dialog.dismiss();
					}
				});
				
				dia.show();
			}
		});
		
		updateButton.setOnClickListener(new OnClickListener()
		{
			
			@Override
			public void onClick(View v)
			{
				setCheckCardUpdate();
			}
		});
	}
	
	/**
	 * 체크카드를 삭제한다.
	 */
	private void setCheckCardDeleteData()
	{
		// 체크카드 연결된 내역들을 수정이나 삭제 못하게 막는다.
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("deleteyn", "1");
		
		String [] whereArgs1 = new String[]{
				BDConstents.CHECK_TYPE, data.getName()};
		
		sql.update(CheckCardUpdataActivity.this, 
				"in_out", map, "type = ? and moneykind = ?", whereArgs1);
		
		sql.update(CheckCardUpdataActivity.this, 
				"in_out", map, "linktype = ? and moneykind = ?", whereArgs1);
		
		String [] whereArgs = new String[]{data.getId() + ""};
		sql.delete(CheckCardUpdataActivity.this, "check_card", "id = ?", whereArgs);
		
		// 세부체크카드 테이블에서도 삭제한다
		String [] whereArgs2 = new String[]{data.getId()};
		sql.delete(this, "checkcard_detail", "linkid = ?", whereArgs2);
		
		// 자산이 삭제 되면 메인 화면 셋팅 값도 같이 삭제한다.
		WidgetGetSqlQuery widgetQuery = new WidgetGetSqlQuery(superContext);
		widgetQuery.setManagerDelete(data.getName(),WidgetGetSqlQuery.CHECKCARD);
	}
	
	/**
	 * 체크카드를 수정 한다.
	 */
	private void setCheckCardUpdate()
	{
		boolean nameOverlap = false;
		
		nameOverlap = BDUtil.getOverlapCheck(sql, this, 
				"SELECT name FROM check_card WHERE name = '" + BDUtil.getApostrophe(name.getText().toString()) + "';");
		
		if (nameOverlap) 
		{
			if (!name.getText().toString().equals(data.getName()))
			{
				BDUtil.showDialog(this, "확인", "동일한 카드 이름이 존재 합니다.");
				name.setText(data.getName());
				return;
			}
		}
		
		if (orderEditText.getText().equals("") || orderEditText.getText().length() < 1
				|| Integer.parseInt(orderEditText.getText().toString()) < 1 || Integer.parseInt(orderEditText.getText().toString()) > 999 )
		{
			BDUtil.showDialog(superContext, "확인", "표시순위를 제대로 입력해주세요.(1~999)");
			return;
		}
		
		new ShowDialog().execute(2);
	}

	private void setCheckCardUpdateData()
	{
		sql.selectMapTile(this, "SELECT id FROM bankbook WHERE name = '"
				+ BDUtil.getApostrophe(linkTextView.getText().toString()) + "';", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int idIdx = c.getColumnIndex("id");
				
				c.moveToFirst();
				int id = -1;
				
				for (int i = 0; i < c.getCount(); i++)
				{
					id = c.getInt(idIdx);
					c.moveToNext();
				}
				
				if (id > -1)
				{
					HashMap<String, String> map = new HashMap<String, String>();
					map.put("banklink", id + "");
					map.put("name", name.getText().toString());
					String [] whereArgs = new String[]{data.getId() + ""};
					sql.update(CheckCardUpdataActivity.this, "check_card", map, "id = ?", whereArgs);
				}
			}
		});
		
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("name", name.getText().toString());
		map.put("count", orderEditText.getText().toString());
		
		String [] whereArgs2 = new String[]{data.getId()};
		
		// 세부 통장 테이블에 데이터를 수정한다.
		sql.update(superContext, "checkcard_detail", map, "linkid = ?", whereArgs2);
		
		// 자산이 수정되면 메인 화면 셋팅 값도 같이 수정한다.
		WidgetGetSqlQuery widgetQuery = new WidgetGetSqlQuery(superContext);
		widgetQuery.setManagerUpdate(data.getName(), name.getText().toString(), WidgetGetSqlQuery.CHECKCARD);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		super.onActivityResult(requestCode, resultCode, data);
		
		if (requestCode == REQUEST_CHECKCARD)
		{
			if (resultCode == Activity.RESULT_OK)
			{
				String selectData = data.getStringExtra(RadioDialogActivity.RADIOSTRING);
				linkTextView.setText(selectData);
			}
		}
	}
	
	/**
	 * 통장 리스트 아답터
	 * @author hyojun
	 *
	 */
	private class BankBookListAdapter extends ArrayAdapter<BankbookData>
	{
		private ArrayList<BankbookData> bankbookList;

		public BankBookListAdapter(Context context, int textViewResourceId,
				ArrayList<BankbookData> list)
		{
			super(context, textViewResourceId, list);
			bankbookList = list;
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent)
		{
			View v  = convertView;
			if (v == null)
			{
				LayoutInflater li = (LayoutInflater) getContext().getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
				v = li.inflate(R.layout.list_item_bankbook, null);
			}
			
			BankbookData data = bankbookList.get(position);
			TextView name = (TextView) v.findViewById(R.id.bankbookName);
			TextView money = (TextView) v.findViewById(R.id.bankbookMoney);
			TextView flag = (TextView) v.findViewById(R.id.bankbookFlag);
			
			name.setText(data.getName());
			money.setText(BDUtil.getWon(data.getMoney()) + shape);
			
			if (data.getFlag().equals("0"))
			{
				flag.setTextColor(getResources().getColor(R.color.inmoney));
				flag.setText("자산포함");
			}
			else
			{
				flag.setTextColor(getResources().getColor(R.color.outmoney));
				flag.setText("미포함");
			}
			
			return v;
		}
	}
	
	/**
	 * 다이얼로그 뛰우기 
	 */
	private class ShowDialog extends AsyncTask<Integer, Integer, Integer>{
		ProgressDialog dialog = null;
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			dialog = new ProgressDialog(CheckCardUpdataActivity.this);
			dialog.setCancelable(false);
			dialog.setMessage("Loading...");
			dialog.show();
		}
		
		@Override
		protected Integer doInBackground(Integer... arg0) {
			
			if (arg0[0] == 0)
			{
				setData();
				return 0;
			}
			else if (arg0[0] == 1)
			{
				try
				{
					sql.beginTansaction(superContext);
					
					setCheckCardDeleteData();
					
					sql.setTransactionSuccessful();
				} catch (Exception e)
				{
					return -1;
				} finally {
					try 
					{
						sql.endTransaction(superContext);
					} catch (Exception e) 
					{
						return -1;
					}
				}
				return 1;
			}
			else if (arg0[0] == 2)
			{
				try
				{
					sql.beginTansaction(superContext);
					
					setCheckCardUpdateData();
					
					sql.setTransactionSuccessful();
				} catch (Exception e)
				{
					return -1;
				} finally {
					try 
					{
						sql.endTransaction(superContext);
					} catch (Exception e) 
					{
						return -1;
					}
				}
				return 2;
			}
			
			return null;
		}

		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);
			
			dialog.dismiss();
			
			if (result == -1)
			{
				BDUtil.btnEnable = true;
				BDUtil.asyncFlag = 0;
				
				BDUtil.showDialog(superContext, "오류", "데이터 저장에 실패했습니다.");
			}
			else if (result == 0)
			{
				name.setText(data.getName());
				linkTextView.setText(data.getLinkName());
				
				if (data.getOrder().equals("0"))
				{
					orderEditText.setText("999");
				}
				else
				{
					orderEditText.setText(data.getOrder());
				}
				
				if (listView.getFooterViewsCount() > 0)
				{
					listView.removeFooterView(resultView);
					
				}
				
				if (bankbookDataList.size() < 1)
				{
					listView.addFooterView(resultView);
					listView.setFooterDividersEnabled(false);
				}
				else
				{
					
					listView.setFooterDividersEnabled(true);
					listView.setOnItemClickListener(onItemClicklistener);
				}
				
				BankBookListAdapter adapter = new BankBookListAdapter(
						CheckCardUpdataActivity.this, R.layout.list_item_bankbook, bankbookDataList);
				listView.setAdapter(adapter);
				adapter.notifyDataSetChanged();
			}
			else if (result == 1)
			{
				BDUtil.showDialogFinish(CheckCardUpdataActivity.this, "삭제", "체크카드가 삭제 되었습니다.");
			}
			else if (result == 2)
			{
				BDUtil.showDialogFinish(CheckCardUpdataActivity.this, "수정", "체크카드가 수정 되었습니다.");
			}
		}
	}

	@Override
	protected void tipButton()
	{
	}
}
